# 用户管理路由

from fastapi import APIRouter, UploadFile, File
from models import Device, FirmwareUpdate
from utils.mqtt_client import mqtt_client

router = APIRouter()


@router.post("/devices/{device_id}/update")
async def initiate_update(
        device_id: str,
        version: str,
        firmware: UploadFile = File(...)
):
    # 保存固件文件
    file_path = f"firmware/{device_id}_{version}.bin"
    with open(file_path, "wb") as f:
        f.write(await firmware.read())

    # 创建升级记录
    device = await Device.get(device_id=device_id)
    update = await FirmwareUpdate.create(
        device=device,
        version=version,
        file_path=file_path
    )

    # 通过MQTT发送升级指令
    mqtt_client.client.publish(
        f"devices/{device_id}/update/command",
        payload=f"{version},{file_path}"
    )
    return {"message": "Update initiated"}